<template>
  <div class="login-container">
    <div class="background">
      <img :src="imgSrc" width="100%" height="100%" alt="">
    </div>
    <div class="login-box">
      <h3>管理员登录</h3>
      <el-form label-position="right" ref="loginFormRef" :model="loginForm" :rules="loginFormRules">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            prefix-icon="el-icon-user"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            prefix-icon="el-icon-goods"
            type="password"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" round @click="login">登录</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      imgSrc: require('../assets/images/login.jpg'),
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('admin/login', this.loginForm)
        if (res.meta.status !== 200) return this.$message.error('登录失败！')
        this.$message.success('登录成功')
        window.sessionStorage.setItem('token', res.data.token)
        window.sessionStorage.setItem('id', res.data._id)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  width: 100%;
  height: 100%;
}
.background {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.login-box {
  z-index: 1;
  position: absolute;
  width: 400px;
  height: 250px;
  margin-top: 200px;
  padding: 20px;
  left: 50%;
  transform: translateX(-50%);
  h3 {
    height: 30px;
    line-height: 30px;
    text-align: center;
    color: #fff;
    margin-bottom: 20px;
  }
}
.el-button {
  width: 30%;
  float: right;
}
</style>
